package org.busalerter.parser;

import org.busalerter.domain.BusStop;
import org.busalerter.domain.BusTime;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;

/**
 * Created by IntelliJ IDEA.
 * <p/>
 * User: bethella
 * Date: 18/11/11
 * Time: 16:23
 */
public class DataScraperImpl implements DataScraper {

    public void updateBusStop(BusStop busStop) {

        Document doc;
        try {
            doc = Jsoup.connect("http://accessible.countdown.tfl.gov.uk/arrivals/" + busStop.getBusStopCode()).get();

            Elements result = doc.select("tbody");
            Element tbody = result.first();

            if (tbody!=null) {

                Elements rows = tbody.select("tr");

                busStop.getBusTimes().clear();

                for (Object obj : rows.toArray()) {
                    Element element = (Element) obj;

                    BusTime busTime = new BusTime();
                    busTime.setRoute(element.select("td[class=resRoute]").first().text());
                    busTime.setDestination(element.select("td[class=resDir]").first().text());
                    busTime.setEtaText(element.select("td[class=resDue]").first().text());

                    if (busTime.getEtaText() != null) {
                        if (busTime.getEtaText().equalsIgnoreCase("due")) {
                            busTime.setEtaMinutes(0);
                        } else {
                            // attempt to parse time
                            String sanitizedText = busTime.getEtaText().replaceAll("\\D+", "");

                            if (sanitizedText != null) {
                                busTime.setEtaMinutes(Integer.parseInt(sanitizedText));
                            }
                        }

                    }

                    busStop.getBusTimes().add(busTime);
                }
            } else {

                // todo log warn - no results found
            }

        } catch (IOException e) {
            // todo log error that bustimes could not be updated?
            e.printStackTrace();
        }
    }
}
